package com.cop4331.social;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Inbox for old user messages that were not deleted.
 * 
 */
public class MessageOld extends Activity {

	public static String un;
	ListView newlist;
	EditText dmessage;
	EditText dsub;
	EditText dfrom;
	TextView nomessages;
	TextView tv_tutor;
	Button reply;
	Button delete;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// XML associated with MessageOld
		setContentView(R.layout.messageold);
		
		// ListViews
		newlist = (ListView) findViewById(R.id.messageList);
		nomessages = (TextView) findViewById(R.id.nomessages);

		// Retreive current term from SQLite Database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();

		un = user.get("name");

		Parcelable state = newlist.onSaveInstanceState();

		// Assign adapter to ListView
		try {

			// Set adapter
			// Adapter comes from SimpleAdapter_Ext Class

			List<Map<String, Object>> data = getData();

			System.out.println(data);

			if (data.size() != 0)
				nomessages.setVisibility(View.GONE);

			newlist.setAdapter(new SimpleAdapter(this, getData(),
					R.layout.messagelist, new String[] { "from", "sub", "to",
							"message", "status" }, new int[] { R.id.from,
							R.id.sub }));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		newlist.onRestoreInstanceState(state);

		// Give the listview functionality when a user clicks it
		newlist.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {

				// Retrieve the current selected item details
				final Map<String, Object> item = (Map<String, Object>) parent
						.getItemAtPosition(pos);
				
				// Create dialog to show message to user
				Dialog dialog = new Dialog(MessageOld.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.messagedialog);
				dialog.setCancelable(true);

				dfrom = (EditText) dialog.findViewById(R.id.dfrom);
				dsub = (EditText) dialog.findViewById(R.id.dsub);
				dmessage = (EditText) dialog.findViewById(R.id.dmessage);

				delete = (Button) dialog.findViewById(R.id.b_delete);
				reply = (Button) dialog.findViewById(R.id.b_reply);
				
				// Set dialog info
				dfrom.setText(item.get("from").toString());
				dsub.setText(item.get("sub").toString());
				dmessage.setText(item.get("message").toString());
				
				// Reply Button
				reply.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						// Bundle the selected tutor for the
						// ScheduleRequestActivity (We will add to the database
						// in the next frame)
						Bundle b = new Bundle();
						b.putString("sender", item.get("from").toString());
						b.putString("subject", item.get("sub").toString());
						b.putString("id", item.get("id").toString());

						// Goto the ScheduleRequestActivity
						Intent log = new Intent(getApplicationContext(),
								ReplyMessageActivity.class);
						log.putExtras(b);
						startActivity(log);
					}
				});
	
				// Delete message button
				delete.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						UserFunctions uf = new UserFunctions();
						uf.deleteMessage(item.get("id").toString());
						
						// Make sure to reload tab with old tab selected
						Bundle b = new Bundle();
						b.putString("last", "1");

						Intent log = new Intent(getApplicationContext(),
								MessageNotifications.class);
						log.putExtras(b);
						startActivity(log);
						finish();

					}
				});

				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

			}
		});
	}

	// -----------------------------------------------
	// GETDATA
	// Retreives and returns list of new messages from the database
	// -----------------------------------------------
	private List<Map<String, Object>> getData() throws Exception {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // Used
																				// to
																				// store
																				// the
																				// available
																				// tutors
																				// from
																				// Database

		// Retreive new messages
		UserFunctions uf = new UserFunctions();
		JSONObject json = uf.retreiveMessages(un, "old");

		// Stores size of the list returned from Database
		int size;

		try {
			size = Integer.parseInt(json.getString("size"));
			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_mes = json.getJSONObject("" + i);

					// Place each object in the HashMap
					map.put("to", json_mes.getString("to"));
					map.put("from", json_mes.getString("from"));
					map.put("sub", json_mes.getString("subject"));
					map.put("message", json_mes.getString("message"));
					map.put("status", json_mes.getString("status"));
					map.put("id", json_mes.getString("id"));

					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return list;
	}
}
